<template>
  <div class="archived-contracts">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>已归档合同</h2>
        <button @click="goBack" class="btn btn-secondary">
          <i class="fa fa-arrow-left mr-2"></i>返回上一级
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载合同中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 调试信息 - 开发时使用，生产环境可移除 -->
    <div v-if="!loading && debugInfo" class="debug-info p-3 bg-light rounded-lg shadow-sm">
      <p class="text-sm text-gray-600">合同数量: {{ contracts.length }}</p>
    </div>

    <!-- 合同列表 -->
    <div v-if="!loading && contracts.length > 0" class="card mt-4">
      <div class="card-body">
        <div class="contracts-table overflow-x-auto">
          <table class="table w-full border-collapse" style="table-layout: fixed;">
            <thead class="bg-gray-50">
            <tr>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同ID</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同名称</th>
<!--              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">项目经理</th>-->
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">创建时间</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">归档时间</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="contract in contracts" :key="contract.id" class="border-b border-gray-200 hover:bg-gray-50 transition-colors duration-200">
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.id || '无ID' }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.name || '无名称' }}</td>
<!--              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.projectManager?.name || '未指定' }}</td>-->
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ formatDate(contract.createTime) || '无时间' }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ formatDate(contract.archiveTime || contract.updateTime) || '无时间' }}</td>
              <td class="py-3 px-4 border-b border-gray-200">
                <button @click="viewContract(contract.id)" class="btn btn-info btn-sm">
                  <i class="fa fa-eye mr-2"></i>查看详情
                </button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件 -->
        <div class="pagination mt-3 d-flex justify-content-between">
          <div>
            每页显示 {{ pageSize }} 条，共 {{ totalItems }} 条
          </div>
          <div>
            <button
                @click="prevPage"
                :disabled="currentPage === 0"
                class="btn btn-sm btn-outline-secondary"
            >
              <i class="fa fa-chevron-left"></i> 上一页
            </button>
            <span class="mx-2">
              第 {{ currentPage + 1 }} 页，共 {{ totalPages }} 页
            </span>
            <button
                @click="nextPage"
                :disabled="currentPage === totalPages - 1"
                class="btn btn-sm btn-outline-secondary"
            >
              下一页 <i class="fa fa-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 无合同提示 -->
    <div v-else-if="!loading && contracts.length === 0" class="card mt-4">
      <div class="card-body">
        <div class="empty-message text-center py-4">
          <i class="fa fa-archive text-muted display-4 mb-3"></i>
          <h4>暂无已归档的合同</h4>
          <p class="text-muted">没有已归档的合同记录</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'CustomerArchivedContracts',
  setup() {
    const store = useStore()
    const router = useRouter()

    const loading = ref(true)
    const errorMessage = ref('')
    const contracts = ref([])
    const currentPage = ref(0)
    const pageSize = ref(10)
    const totalPages = ref(1)
    const totalItems = ref(0)
    const debugInfo = ref(false) // 生产环境设为false
    const customerId = ref(null)

    // 配置请求头
    const setupRequestHeaders = () => {
      if (store.state.user) {
        axios.defaults.headers.common['X-Customer-Id'] = store.state.user.id
      }
    }

    // 返回上一级
    const goBack = () => {
      router.push('/customer/home')
    }

    // 获取已归档的合同数据
    const fetchArchivedContracts = () => {
      loading.value = true
      errorMessage.value = ''

      if (!customerId.value) {
        errorMessage.value = '用户信息加载中，请稍后...'
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/customer-archived/${customerId.value}`, {
        headers: {
          'X-Customer-Id': customerId.value
        },
        params: {
          page: currentPage.value,
          size: pageSize.value
        }
      })
          .then(response => {
            if (response.data && response.data.content) {
              contracts.value = response.data.content
              totalItems.value = response.data.totalElements
              totalPages.value = response.data.totalPages
            } else {
              contracts.value = response.data || []
              totalItems.value = (response.data || []).length
              totalPages.value = Math.ceil(totalItems.value / pageSize.value)
            }
            console.log('合同数据归档时间检查:', contracts.value.map(c => c.archiveTime))
          })
          .catch(error => {
            console.error('获取已归档的合同失败', error)
            if (error.response) {
              errorMessage.value = error.response.data?.message || '获取合同失败，请稍后再试'
            } else {
              errorMessage.value = '网络错误，请检查连接'
            }
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 查看合同详情
    const viewContract = (contractId) => {
      router.push(`/customer/contracts/${contractId}/archived-detail`)
    }

    // 分页操作
    const prevPage = () => {
      if (currentPage.value > 0) {
        currentPage.value--
        fetchArchivedContracts()
      }
    }

    const nextPage = () => {
      if (currentPage.value < totalPages.value - 1) {
        currentPage.value++
        fetchArchivedContracts()
      }
    }

    // 格式化日期（增强错误处理）
    const formatDate = (dateString) => {
      if (!dateString) return ''
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) {
          return '日期格式错误'
        }
        return date.toLocaleString()
      } catch (e) {
        console.error('日期格式化错误:', e)
        return '日期格式错误'
      }
    }

    onMounted(() => {
      if (store.state.user) {
        customerId.value = store.state.user.id
        setupRequestHeaders()
        fetchArchivedContracts()
      }
    })

    // 监听用户信息变化
    watch(() => store.state.user?.id, () => {
      if (store.state.user) {
        customerId.value = store.state.user.id
        fetchArchivedContracts()
      }
    })

    return {
      loading,
      errorMessage,
      contracts,
      currentPage,
      pageSize,
      totalPages,
      totalItems,
      goBack,
      viewContract,
      prevPage,
      nextPage,
      formatDate,
      debugInfo
    }
  }
}
</script>

<style scoped>
/* 样式部分与之前保持一致，此处省略以避免重复 */
/* 如需完整样式，请参考上一次回复中的style标签内容 */
</style>

<style scoped>
.header {
  background-color: #f8f9fa;
  padding: 15px;
  border-bottom: 1px solid #dee2e6;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  padding: 10px 15px;
  color: #721c24;
  background-color: #f8d7da;
  border-radius: 4px;
  margin: 15px 0;
  display: flex;
  align-items: center;
}

.debug-info {
  margin: 15px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.card {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #dee2e6;
}

.contracts-table {
  margin-top: 15px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-message {
  padding: 30px 0;
}

.empty-message i {
  color: #adb5bd;
}

.empty-message h4 {
  color: #495057;
  margin-bottom: 10px;
}

.empty-message p {
  color: #6c757d;
  margin-bottom: 0;
}

/* 表格样式优化 */
.table {
  width: 100%;
  border-collapse: collapse;
}

.table th, .table td {
  padding: 0.75rem;
  vertical-align: middle;
  border-bottom: 1px solid #e5e7eb;
  word-break: break-word;
}

.table th {
  font-weight: 500;
  color: #4b5563;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 2px solid #e5e7eb;
}

.table tbody tr {
  vertical-align: middle;
}

/* 按钮样式优化 */
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0.375rem 0.75rem;
  font-size: 0.875rem;
  font-weight: 500;
  line-height: 1.5;
  border-radius: 0.25rem;
  transition: all 0.2s ease-in-out;
  border: 1px solid transparent;
  cursor: pointer;
}

.btn-info {
  color: #fff;
  background-color: #17a2b8;
  border-color: #17a2b8;
}

.btn-info:hover {
  background-color: #138496;
  border-color: #117a8b;
}

.btn-outline-secondary {
  color: #6c757d;
  background-color: transparent;
  border-color: #6c757d;
}

.btn-outline-secondary:hover {
  color: #fff;
  background-color: #6c757d;
  border-color: #6c757d;
}
</style>